package lee.vioson.ebook.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.laiyifen.lyftoast.ToastUtils
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.data.AppEvent
import lee.vioson.ebook.ui.components.LauncherScreen
import lee.vioson.ebook.ui.components.Loading
import lee.vioson.ebook.viewmodels.MainAppViewModel

/**
 *Author:viosonlee
 *Date:2023/6/1
 *DESCRIPTION:
 */
@Composable
fun MainApp(
    viewModel: MainAppViewModel = viewModel(),
    appContainer: AppContainer,
    navHostController: NavHostController
) {
    appContainer.appEvent = AppEvent(
        showToast = { string ->
            viewModel.sendEvent(MainAppViewModel.Event.OnShowToast(string))
        },
        showLoading = { showLoading, loadingMessage ->
            viewModel.sendEvent(MainAppViewModel.Event.OnLoadingChange(showLoading, loadingMessage))
        },
        reLogin = {
            viewModel.sendEvent(MainAppViewModel.Event.OnRequestLogin)
        }
    )
    val context = LocalContext.current
    val state by viewModel.state.collectAsState()
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppTheme.colors.background)
    ) {

        LaunchedEffect(key1 = state.toast, key2 = state.toastCount, block = {
            ToastUtils.show(context, state.toast)
        })

        LaunchedEffect(key1 = state.reLogin, block = {
            //re login
        })

        Loading(showLoading = state.showLoading, progressModifier = Modifier.size(60.dp)) {
            if (state.showLauncher) {
                LauncherScreen(appContainer = appContainer) {
                    viewModel.sendEvent(MainAppViewModel.Event.OnLauncherDismiss)
                }
            } else {
                MainAnimateNavGraph(
                    modifier = Modifier.fillMaxSize(),
                    appContainer = appContainer,
                    navController = navHostController
                )
            }
        }
    }
}